/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.ban.handler;

import cn.ac.iie.di.ban.dao.MySQLDao;
import cn.ac.iie.di.ban.tools.MySQLHelper;
import com.alibaba.fastjson.JSON;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Logger;
import net.sf.json.JSONObject;

/**
 *
 * @author xiaoliang
 */
public class SE2DBWorkerMysqlCommon extends SE2DBWorker {

    private static org.apache.log4j.Logger logger = Logger.getLogger(SE2DBWorkerMysqlCommon.class.getName());
    private MySQLHelper mySQLHelper;
    private MySQLDao mySQLDao;
    private Map<String, Object> contentMsg = new HashMap<>(1);
    private Map<String, Object> whereMsg = new HashMap<>(1);

    public SE2DBWorkerMysqlCommon(HttpSe2DBHandler httpSe2DBHandler, String pDWType) {
        super(httpSe2DBHandler, pDWType);
    }

    @Override
    public void init() throws Exception {
        mySQLHelper = MySQLHelper.getMySQLHelper(
                HttpSe2DBHandler.getDriver(),
                HttpSe2DBHandler.getUrl(),
                HttpSe2DBHandler.getUser(),
                HttpSe2DBHandler.getPwd(),
                HttpSe2DBHandler.getInitSize(),
                HttpSe2DBHandler.getMaxSize());
        mySQLDao = new MySQLDao(mySQLHelper, load2DBEntity);
        mySQLDao.init();
        mySQLDao.getDBCols();
    }

    @Override
    public void loadData0() {
        Map result = new HashMap(5);
        String rflag = "";
        try {
            start_time = System.currentTimeMillis();
            Map<String, Object> record = docRecordSet.get(0);
            rflag = record.get("rflag").toString();
            String scope = record.get("scope").toString();
            String opration = record.get("opration").toString();//new,update,search,del
            String content = record.get("content").toString();//内容
            String condition = record.get("condition").toString();//条件
            if (!"".equals(content)) {
                contentMsg = JSON.parseObject(content);
            }
            if (!"".equals(condition)) {
                whereMsg = JSON.parseObject(condition);
            }
//            for (String col : contentMsg.keySet()) {
//                if (load2DBEntity.getColunmsFromDB().get(col) == null) {
//                    result.put("status", "error");
//                    result.put("detail", "receive content params error : " + col);
//                    JSONObject jsonObject = JSONObject.fromObject(result);
//                    HttpSe2DBHandler.result.put(rflag, jsonObject.toString());
//                    logger.error(result.get("status") + " Detail: " + result.get("detail"));
//                    docRecordSet.clear();
//                    return;
//                }
//            }
//            for (String col : whereMsg.keySet()) {
//                if (load2DBEntity.getColunmsFromDB().get(col) == null) {
//                    result.put("status", "error");
//                    result.put("detail", "receive condition params error : " + col);
//                    JSONObject jsonObject = JSONObject.fromObject(result);
//                    HttpSe2DBHandler.result.put(rflag, jsonObject.toString());
//                    logger.error(result.get("status") + " Detail: " + result.get("detail"));
//                    docRecordSet.clear();
//                    return;
//                }
//            }
            if ("new".equals(opration)) {
//                contentMsg.put("ut", System.currentTimeMillis() / 1000);
                result = mySQLDao.saveRecord(contentMsg);
            } else if ("update".equals(opration)) {
//                contentMsg.put("ut", System.currentTimeMillis() / 1000);
//                whereMsg.put("validity", 1);
//                if (contentMsg.get("req_id") != null && "task".equals(scope)) {
//                    String req_id = contentMsg.remove("req_id").toString().trim();
//                    whereMsg.put("validity", 1);
//                    Set<String> returnCols = new HashSet();
//                    returnCols.add("req_id");
//                    result = mySQLDao.findMsgCommon(returnCols, whereMsg);
////                    if (!"".equals(result.get("data").toString())) {
////                        Object obj = ((ArrayList) result.get("data")).get(0);
////                        Map map = (Map) obj;
////                        Object reds = map.get("req_id");
////                        String req_ids = (reds == null) ? "" : reds.toString().trim();
////                        if (req_ids.contains(req_id)) {
////                            result.clear();
////                            result.put("status", "exist");
////                            result.put("detail", req_id + " exist");
////                        } else {
////                            StringBuilder str = new StringBuilder();
////                            str.append(req_ids).append(",").append(req_id);
////                            contentMsg.put("req_id", str.toString().trim());
////                            result = mySQLDao.updateRecord(contentMsg, whereMsg);
////                        }
////                    } else {
////                        result.clear();
////                        result.put("status", "notexist");
////                        result.put("detail", "this msg is not in " + load2DBEntity.getTable());
////                    }
//                } else {
                result = mySQLDao.updateRecord(contentMsg, whereMsg);
//                }
            } else if ("search".equals(opration)) {
//                whereMsg.put("validity", 1);
                result = mySQLDao.findMsgCommon(contentMsg.keySet(), whereMsg);
            } else if ("del".equals(opration)) {
                result = delMsg(scope);
            }
            JSONObject jsonObject = JSONObject.fromObject(result);
            HttpSe2DBHandler.result.put(rflag, jsonObject.toString());
            end_time = System.currentTimeMillis();
            logger.info("expect " + opration + " record to " + httpSe2DBHandler.getTable() + " successfully status: " + result.get("status") + " Detail: " + result.get("detail") + " using " + (end_time - start_time) + " ms ");
            docRecordSet.clear();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            result.put("status", "error");
            result.put("detail", e.getMessage() + " project error!");
            JSONObject jsonObject = JSONObject.fromObject(result);
            HttpSe2DBHandler.result.put(rflag, jsonObject.toString());
        }
    }

    public Map delMsg(String scope) {
        Map result = new HashMap(5);

//        Map<String, Object> validity = new HashMap<>(1);
//        validity.put("validity", 0);
//        validity.put("ut", System.currentTimeMillis() / 1000);
        result = mySQLDao.deleteRecord( whereMsg);
        String status = result.get("status").toString();
        if ("succeeded".equals(status)) {
            String detail = result.get("detail").toString();
            result.put("detail", detail.replace("update", "del"));

        }
        return result;
    }

    @Override
    public void freeSource() {
        mySQLHelper.close(mySQLDao.getConn());
    }
}
